import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'

let reducer = (state, action) => {
    let NewState = JSON.parse(JSON.stringify(state))
    switch(action.type) {
        case "SET_CLASSIFY":
            NewState.classifyList = action.list
            return NewState
        case "ADD_CAR_ITEM": 
            // 判断是否要去重
            let flag = NewState.carList.some(item => item.goods_id === action.item.goods_id)
            if (flag) {
                // findIndex
                let index = NewState.carList.findIndex(item => item.goods_id === action.item.goods_id)
                NewState.carList[index].count += 1
            } else {
                let items = action.item
                items.count = 1
                items.flag = true
                NewState.carList.push(items)
            }

            // 计算总数量
            NewState.allCount = NewState.carList.reduce((prev, next) => {
                return prev + next.count
            }, 0)

            // 计算总价格
             NewState.allPrice = NewState.carList.reduce((prev, next) => {
                return prev + next.count * next.goods_price
            }, 0)

            return NewState
        case "CHANGE_ITEM_CHECKED":
            NewState.carList[action.index].flag = action.flag

             // 计算总数量
             NewState.allCount = NewState.carList.reduce((prev, next) => {
                if (next.flag) {
                    return prev + next.count
                } else {
                    return prev
                }
               
            }, 0)

            // 计算总价格
             NewState.allPrice = NewState.carList.reduce((prev, next) => {
                if (next.flag) {
                    return prev + next.count * next.goods_price
                } else {
                    return prev
                }
            }, 0)
            return NewState
        default:
            return state
    }
}

let initState = {
    classifyList: [],
    carList: [],
    allCount: 0,
    allPrice: 0
}

let store = createStore(reducer, initState, applyMiddleware(thunk))

export default store